//
//  emoticonManager.swift
//  SinaWebo
//
//  Created by mis on 16/3/23.
//  Copyright © 2016年 mis. All rights reserved.
//

import UIKit

class EmoticonManager: NSObject {
    static let emoticonManager: EmoticonManager = EmoticonManager()
    
    lazy var packages = [EmoticonPackage]()
    
    func textToImageText(str: String, font: UIFont) -> NSAttributedString {
        let pattern = "\\[.*?\\]"
        let regex = try! NSRegularExpression(pattern: pattern, options: [])
        let result = regex.matchesInString(str, options: [], range: NSMakeRange(0, str.characters.count))
        print(result)
        let strM = NSMutableAttributedString(string: str)
        var count = result.count - 1
        while count >= 0 {
            let range = result[count].rangeAtIndex(0)
            let subStr = (str as NSString).substringWithRange(range)
            print(subStr)
            if let emoticon = getEmoticon(subStr) {
                let imageText = EmoticonAttachment().emoticonimageText(emoticon, font: font)
                strM.replaceCharactersInRange(range, withAttributedString: imageText)
            }
            count--
        }
        return strM
    }
    
    override init() {
        super.init()
        loadPackages()
    }
    
    func getEmoticon(string: String) -> Emoticon? {
        for p in EmoticonManager().packages {
            let list = p.emoticonList.filter({ (em) -> Bool in
                return em.chs == string
            })
            if let e = list.last {
                return e
            }
        }
        return nil
    }
    
    private func loadPackages() {
        let patch = NSBundle.mainBundle().pathForResource("emoticons", ofType: "plist", inDirectory: "Emoticons.bundle")
        let dict = NSDictionary(contentsOfFile: patch!)!
        if let array = dict["packages"] as? [[String: AnyObject]] {
            for item in array {
                let id = item["id"] as! String
                loadPackage(id)
            }
        }
    }
    
    private func loadPackage(id: String) {
        let patch = NSBundle.mainBundle().pathForResource("Info", ofType: "plist", inDirectory: "Emoticons.bundle/\(id)")
        let dict = NSDictionary(contentsOfFile: patch!)!
        let name = dict["group_name_cn"] as! String
        let array = dict["emoticons"] as! [[String: String]]
        let e = EmoticonPackage(id: id, name: name, emoticons: array)
        packages.append(e)
    }
}
